<template>
  <div class="app-container contract-supervision">
    <div>
      <avue-form
        :option="option"
        v-model="queryParams"
        ref="searchForm"
        v-show="showSearch"
        @keydown.enter="getList"
      >
        <!-- <template #productId>
          <el-select
            v-model="queryParams.productId"
            placeholder="请选择产品"
            class="w-full"
            suffix-icon="Search"
            remote-show-suffix
            :suffix-transition="false"
            filterable
            remote
            clearable
            :remote-method="val => getProduct(val)"
          >
            <el-option
              v-for="item in productSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div>
                <span>{{ item.name }}</span>
              </div>
            </el-option>
          </el-select>
        </template> -->
        <template #menu-form>
          <el-button icon="Search" type="primary" @click="getList" class="m-l-3"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleEmpty(searchForm)"
            >重置</el-button
          >
          <el-button icon="Download" @click="exportFile(searchForm)"
            >导出</el-button
          >
        </template>
      </avue-form>

      <el-row :gutter="10" class="my-15px">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="EditPen"
            @click="handleCheck"
            :disabled="disDelete"
            v-hasPermi="['qualityManage:contract:supervision']"
            >批量审核</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Upload"
            plain
            @click="
              () => {
                uploadDia.open = true
                uploadDia.title = '导入合同'
                uploadDia.uploadType = 'contract'
              }
            "
            >批量上传合同</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Upload"
            plain
            @click="
              () => {
                uploadDia.open = true
                uploadDia.title = '导入备注'
                uploadDia.uploadType = 'remark'
              }
            "
            >批量备注</el-button
          >
        </el-col>

        <right-toolbar @queryTable="getList" v-model:showSearch="showSearch">
          <el-tooltip
            class="item"
            effect="dark"
            :content="'自定义列表'"
            placement="top"
          >
            <el-button circle icon="Menu" @click="handleTable()" />
          </el-tooltip>
        </right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="tableList"
        stripe
        border
        @selection-change="handleSelectionChange"
        @row-dblclick="dbclickRow"
      >
        <el-table-column
          type="selection"
          width="40"
          align="center"
          fixed="left"
        />
        <!-- <el-table-column
          prop="contractOrderNumber"
          label="合同(订单)编号"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="customerCreditCode"
          label="客户税号"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" min-width="230">
        </el-table-column>
        <el-table-column prop="approvalResult" label="审核情况" width="130">
          <template #default="scope">
            <div>
              <el-tooltip
                class="box-item"
                effect="dark"
                :disabled="!scope.row.approvalOpinion"
                :content="scope.row.approvalOpinion"
                placement="top"
              >
                <span v-if="scope.row.approvalResult"
                  >已审 (<dict-drop
                    class="inline-block"
                    :options="supervision_approval"
                    :value="scope.row.approvalResult"
                  ></dict-drop
                  >)</span
                >
                <span v-else>未审</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="contractList" label="合同上传情况" width="130">
          <template #default="scope">
            <span v-if="scope.row.contractList.length > 0">
              已上传(<el-link
                type="primary"
                @click="viewContract(scope.row.contractList)"
                >查看</el-link
              >)
            </span>
            <span v-else>未上传</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="contractRemark"
          label="备注内容"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column label="产品名称" prop="name" width="180" />
        <el-table-column label="服务时段" prop="serviceDateArr" width="190">
          <template #default="scope">
            <div>
              <span v-if="scope.row.startDate && scope.row.endDate"
                >{{ scope.row.startDate }}至{{ scope.row.endDate }}</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="businessType"
          label="业务板块"
          width="130"
          align="center"
        >
          <template #default="scope">
            <dict-drop
              :options="order_business_type"
              :value="scope.row.businessType"
            ></dict-drop>
          </template>
        </el-table-column>
        <el-table-column prop="transactionName" label="销售人" width="100">
        </el-table-column>
        <el-table-column prop="mainContactPhone" label="联系电话" width="120">
        </el-table-column>
        <el-table-column prop="customerLevel" label="纳税人等级" width="100">
          <template #default="scope">
            <dict-drop
              :options="custome_star"
              :value="scope.row.customerLevel"
            ></dict-drop>
          </template>
        </el-table-column>
        <el-table-column
          prop="deptName"
          label="归属公司"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="taxdeptName"
          label="所属税务局"
          width="180"
          align="center"
        >
        </el-table-column> -->
        <el-table-column
          v-for="(item, index) in tableCol.filter(item => item.show)"
          :key="index"
          v-bind="item"
        >
          <template #default="scope">
            <div v-if="item.tooltip">
              <el-tooltip
                :disabled="!scope.row.invoiceMsg"
                effect="dark"
                :content="item.tooltip(scope.row)"
                placement="top"
              >
                {{ item.tooltipVal(scope.row) }}
              </el-tooltip>
            </div>
            <div v-if="scope.column.label == '合同上传情况'">
              <span v-if="scope.row.contractList.length > 0">
                已上传(<el-link
                  type="primary"
                  @click="viewContract(scope.row.contractList)"
                  >查看</el-link
                >)
              </span>
              <span v-else>未上传</span>
            </div>
            <div v-if="scope.column.label == '备注内容'">
              <el-tooltip
                class="box-item"
                effect="dark"
                :disabled="!scope.row.contractRemarkTime"
                :content="`备注人:${scope.row.contractRemarkName},备注时间:${scope.row.contractRemarkTime}`"
                placement="top-start"
              >
                <span>{{ scope.row.contractRemark }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="220"
          fixed="right"
          class-name="small-padding"
        >
          <template #default="scope">
            <el-button
              plain
              size="small"
              type="primary"
              icon="CircleCheckFilled"
              @click="handleCheck(scope.row)"
              v-hasPermi="['qualityManage:contract:supervision']"
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              >审核</el-button
            >
            <el-button
              plain
              size="small"
              type="success"
              icon="Upload"
              @click="uploadContract(scope.row)"
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              >上传合同</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog v-model="checkDia" title="审核" width="30%">
      <el-form
        ref="checkRef"
        :model="checkForm"
        :rules="checkRules"
        label-width="140px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="审批结果" prop="approvalResult">
              <el-radio-group v-model="checkForm.approvalResult">
                <el-radio
                  :label="item.value"
                  v-for="(item, index) in supervision_approval"
                  :key="index"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审批意见" prop="approvalOpinion">
              <el-input
                v-model="checkForm.approvalOpinion"
                type="textarea"
                rows="4"
                maxlength="100"
                show-word-limit
                placeholder="请输入审批意见"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkDia = false">取消</el-button>
          <el-button type="primary" @click="saveCheck()"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="viewDia" title="查看合同" width="800">
      <div>
        <el-table
          :data="contractList"
          row-key="rcId"
          default-expand-all
          border
          max-height="500"
          ref="refTable"
        >
          <el-table-column type="expand" width="60">
            <template #default="props">
              <!-- <div>{{ props.row.productList }}</div> -->
              <div>
                <el-table
                  v-if="props.row.fileList && props.row.fileList.length > 0"
                  :data="props.row.fileList"
                  @row-dblclick="(row, column, event) => viewFiles(row.url)"
                  row-class-name="cursor-pointer"
                >
                  <el-table-column
                    type="index"
                    label="序号"
                    width="60"
                    align="center"
                  />
                  <el-table-column label="文件名称" prop="origFileName" />
                  <!-- <el-table-column label="文件大小" prop="fileSize">
                  </el-table-column> -->
                  <!-- <el-table-column
                    label="操作"
                    align="center"
                    width="220"
                    fixed="right"
                    class-name="small-padding"
                  >
                    <template #default="scope">
                      <el-button
                        plain
                        size="small"
                        type="primary"
                        icon="CircleCheckFilled"
                        @click="viewFiles(scope.row.url)"
                        style="padding-left: 0.5rem; padding-right: 0.5rem"
                        >查看</el-button
                      >
                    </template>
                  </el-table-column> -->
                </el-table>
                <div v-else>
                  <el-empty
                    :image-size="50"
                    description="该合同无附件"
                    class="p-y-3"
                  />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="contractName" label="合同名称">
          </el-table-column>
          <el-table-column prop="createBy" label="创建人员" width="100">
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="130"
            fixed="right"
            class-name="small-padding"
          >
            <template #default="scope">
              <el-button
                v-if="!scope.row.rcId"
                plain
                size="small"
                type="primary"
                icon="CircleCheckFilled"
                @click="nuonuoContractDownload(scope.row.contractNum)"
                style="padding-left: 0.5rem; padding-right: 0.5rem"
                >下载诺诺合同</el-button
              >
              <el-button
                icon="View"
                plain
                size="small"
                @click="expandFile(scope.row)"
              >
                <div>查看</div>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDia = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 关联合同 -->
    <SelectContract
      :dialogParam="diaParam"
      @ok="saveFn"
      @close="diaParam.open = false"
    />

    <!-- 导入弹窗 -->
    <el-dialog
      :title="uploadDia.title"
      v-model="uploadDia.open"
      width="400px"
      append-to-body
      @close="closeUpload"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        v-loading="uploadLoading"
        action="#"
        :auto-upload="false"
        :before-upload="beforeAvatarUpload"
        :on-change="handleChange"
        :on-remove="handleRemove"
        :http-request="requestFile"
        :accept="uploadType[uploadDia.uploadType].toString()"
        :multiple="uploadDia.uploadType != 'remark'"
        :show-file-list="true"
        :limit="uploadDia.uploadType == 'remark' ? 1 : 20"
        :on-exceed="handleExceed"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <!-- <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
        <template #tip>
          <div>
            <div
              class="el-upload__tip text-center"
              v-show="uploadDia.uploadType == 'remark'"
            >
              <span class="text-red">一次上传最大支持1个文件</span>
              <el-link
                type="primary"
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                @click="downUrl"
                >下载模板
              </el-link>
            </div>
            <div
              class="el-upload__tip text-center"
              v-show="uploadDia.uploadType == 'contract'"
            >
              <span class="text-red"
                >按文件名称匹配同客户名称的最新一条订单记录,
                一次上传最大支持20个文件</span
              >
            </div>
            <div v-if="uploadDia.message" style="white-space: pre-line">
              导入结果：{{ uploadDia.message }}
            </div>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="closeUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 自定义订单列表弹窗 -->
    <DiaFixTable
      v-model="diaTable.open"
      :dialogParam="diaTable"
      @ok="diaTableFn"
    />

    <!-- 导出列表框 -->
    <el-dialog
      title="导出"
      v-model="showExportTask"
      width="600"
      :close-on-click-modal="false"
      @close="closeExport"
    >
      <el-row
        v-for="item in downloadTaskList"
        :key="item.fileId"
        class="my-20px taskList"
      >
        <el-col :span="8">{{ item.createTime }}</el-col>
        <el-col :span="3">{{
          item.state == '1' ? '下载完成' : '下载中'
        }}</el-col>
        <el-col :span="4" v-if="item.state === '1' && item.url">
          <a :href="item.url" class="color-#4a9eff" download>下载</a></el-col
        >
      </el-row>
      <template #footer>
        <div>
          <el-button type="primary" @click="handleExport">新建导出</el-button>
          <el-button @click="closeExport">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="ContractSupervision">
import { reactive, toRefs, ref, toRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  order_source, //订单来源
  companyOption, //所属公司
  businessTypeOption, //业务类型树
  CONTRACTSUPERVISIONTABLE as INITTABLE //列表数据
} from '@/hooks/dict/order'
import {
  orderSupervisionList,
  supervisionContract,
  supervisionSave,
  importContract,
  importRemark,
  exportSupervision
} from '@/api/supervision/contract'
import { getExportList } from '@/api/rsgl/ygda'
import { downLoadByUrl } from '@/utils/myDownload'
import { listProductSelect } from '@/api/productMange/product'
import {
  contractDownload //合同下载接口
} from '@/api/nuonuoContract/index'
import {
  strToArr,
  viewFile,
  getPricipalId,
  initTable,
  base64Download
} from '@/utils/commo'
import { format, startOfMonth, endOfMonth } from 'date-fns'
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'
import { parseTime, selectDictLabel } from '@/utils/ruoyi'

const commonStore = useCommonStore()

const userStore = useUserStore()
const baseUrl = import.meta.env.VITE_APP_BASE_API
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const { supervision_approval } = proxy.useDict(
  'supervision_approval' //审核结果
)

const now = new Date()

// const userOption = ref({ transactionId: [] })
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    receiptsDateArr: [
      format(startOfMonth(now), 'yyyy-MM-dd'),
      format(endOfMonth(now), 'yyyy-MM-dd')
    ],
    productId: undefined,
    serviceDateArr: [],
    deptId: userStore.userInfo.orgId,
    businessType: undefined
  },
  ids: [],
  selectArr: [],
  total: 0,
  option: {
    labelWidth: '10',
    menuSpan: 6,
    submitBtn: false,
    menuPosition: 'left',
    // gutter: 30,
    emptyBtn: false,
    column: [
      {
        prop: 'contractOrderNumber',
        span: 3,
        placeholder: '订单号',
        type: 'input'
      },
      {
        prop: 'receiptsDateArr',
        type: 'daterange',
        span: 4,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '订单开始时间',
        endPlaceholder: '订单结束时间'
      },
      // {
      //   // label: '性别',
      //   span: 3,
      //   prop: 'productId',
      //   placeholder: '产品',
      //   type: 'select'
      // },
      {
        // label: '性别',
        span: 3,
        prop: 'productName',
        placeholder: '产品'
      },
      {
        prop: 'serviceDateArr',
        type: 'daterange',
        span: 5,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '服务开始时间',
        endPlaceholder: '服务结束时间'
      },
      {
        prop: 'deptId',
        span: 3,
        placeholder: '所属公司',
        type: 'tree',
        defaultExpandAll: true,
        disabled: userStore.userInfo.orgId != 484,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption
      },
      {
        // label: '性别',
        span: 3,
        prop: 'businessType',
        placeholder: '业务板块',
        type: 'tree',
        dicData: businessTypeOption
      },
      // 新增
      {
        span: 3,
        prop: 'approvalResult',
        placeholder: '审核状态',
        type: 'select',
        props: {
          value: 'id',
          label: 'label'
        },
        dicData: [
          { id: '0', label: '未审' },
          { id: '1', label: '已审' }
        ]
      },
      {
        span: 3,
        prop: 'contractList',
        placeholder: '合同上传状态',
        type: 'select',
        props: {
          value: 'id',
          label: 'label'
        },
        dicData: [
          { id: '0', label: '未上传(未备注)' },
          { id: '1', label: '已上传(未备注)' },
          { id: '2', label: '已上传(已备注)' },
          { id: '3', label: '未上传(已备注)' },
          { id: '4', label: '未上传' },
          { id: '5', label: '已上传' }
        ]
      },
      {
        span: 4,
        prop: 'customerName',
        placeholder: '客户名称',
        type: 'input'
      },
      {
        // label: '订单来源',
        span: 4,
        prop: 'source',
        placeholder: '订单来源',
        type: 'select',
        dicData: order_source
      },
      {
        span: 4,
        prop: 'customerCreditCode',
        placeholder: '税号',
        type: 'input'
      }
    ]
  },
  showSearch: true,
  disUpdate: true /* 编辑按钮是否可编辑 */,
  disDelete: true /* 关闭按钮是否可编辑 */,
  loading: false,
  tableList: [],
  productSelect: [],
  diaParam: {},
  checkDia: false, //审批弹窗
  checkForm: {
    approvalOpinion: '',
    approvalResult: '1'
  },
  checkRules: {
    approvalResult: [
      {
        required: true,
        message: '请选择审批结果',
        trigger: 'change'
      }
    ]
  },
  viewDia: false, //查看合同
  contractList: [] //合同列表
})
const {
  queryParams,
  ids,
  selectArr,
  total,
  option,
  showSearch,
  disUpdate,
  disDelete,
  loading,
  tableList,
  productSelect,
  diaParam,
  checkDia,
  checkForm,
  checkRules,
  viewDia,
  contractList
} = toRefs(data)

watch(
  [() => route.query.salesOrderData],
  async () => {
    if (route.query.salesOrderData) {
      queryParams.value = JSON.parse(route.query.salesOrderData)
      getList()
    }
  },
  {
    immediate: true
  }
)

const tableCol = ref(INITTABLE)
// 自定义列表弹窗参数
const diaTable = ref({
  open: false,
  tableName: 'contractSupervisionTable',
  tableCol: tableCol.value,
  initCol: INITTABLE
})

// 自定义列表
const handleTable = () => {
  diaTable.value.open = true
  diaTable.value.tableCol = tableCol.value
}

// 获取列表配置
const diaTableFn = value => {
  tableCol.value = value
}
// 初始化
async function init() {
  // 初始化列表配置
  tableCol.value = initTable(diaTable.value.tableName, INITTABLE)

  // 归属部门
  getList()
}
// 重置
function handleEmpty(formEl) {
  proxy.resetForm('searchForm')
  proxy.resetForm('seniorSearchForm')
  // proxy.$refs.searchForm.resetForm()
  getList()
}

let rafId = null
let lastTime = null
function animloop(currentTime) {
  cancelAnimationFrame(rafId)
  rafId = requestAnimationFrame(animloop)
  // console.log(`现在${currentTime}===${lastTime}`)
  // console.log(`现在${rafId}===`)
  // 每5秒执行一次
  if (!lastTime || currentTime - lastTime >= 5000) {
    // 执行你的逻辑
    exportList()
    // 更新上一次执行的时间
    lastTime = currentTime
  }
  // 五分钟后取消
  if (currentTime - lastTime >= 300000) {
    lastTime = currentTime
    cancelAnimationFrame(rafId)
  }
}

const showExportTask = ref(false)
// 导出文件
function exportFile(query) {
  showExportTask.value = true
  exportList()
  // downLoadByUrl('/ord/supervision/export', queryParams.value, {
  //   fileName: '合同监督的导出'
  // })
}
const handleExport = () => {
  let query = {
    loginUserId: userStore.user.userId,
    type: 'htjd',
    ...queryParams.value
  }
  exportSupervision(query).then(res => {
    proxy.$modal.msgSuccess('正在导出')
    // exportList()
    animloop()
  })
}
const downloadTaskList = ref([])
const exportList = () => {
  getExportList({
    createId: userStore.user.userId,
    type: 'htjd'
  }).then(res => {
    downloadTaskList.value = res.data
  })
}
const closeExport = () => {
  console.log('关闭')
  showExportTask.value = false
  cancelAnimationFrame(rafId)
}

// 获取数据列表
function getList() {
  loading.value = true
  // 所属人员
  // queryParams.value.transactionId = getPricipalId(
  //   userOption.value['transactionId'],
  //   queryParams.value._transactionId
  // ).toString()
  orderSupervisionList(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
    console.log(' tableList.value==>', tableList.value)
  })
  console.log('获取数据')
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disUpdate.value = selection.length != 1
  disDelete.value = !selection.length
}
// 双击行
function dbclickRow(row, column, event) {
  goTo('/sales/indent/salesOrderDetails', {
    salesOrderId: row.id
  })
}

// 展开附件下拉
function expandFile(row) {
  proxy.$refs.refTable.toggleRowExpansion(row)
}

function goTo(url, data) {
  router.push({ path: url, query: data })
}

// 检索产品
function getProduct(value) {
  let data = {
    name: value
  }
  listProductSelect(data).then(e => {
    // console.log('e==>', e.rows)
    productSelect.value = e.rows
  })
}
// 查看合同
function viewContract(contract) {
  console.log('contract==>', contract)
  if (contract.length > 1 || contract[0].fileList.length > 1) {
    viewDia.value = true
    contractList.value = contract
  } else {
    contract[0].rcId
      ? viewFile(contract[0].fileList[0].url, useUserStore().userInfo.nickName)
      : nuonuoContractDownload(contract[0].contractNum)
  }
}
// 预览文件
function viewFiles(url) {
  viewFile(url, useUserStore().userInfo.nickName)
}

/**
 *诺诺合同下载
 * @param {*} id 诺诺编号
 */
function nuonuoContractDownload(id) {
  contractDownload({ contractNo: id }).then(ref => {
    if (ref.code !== 200) return proxy.$modal.msgError('下载失败')
    console.log('合同下载==>', ref)
    // window.open(base64Head + ref.data, '_blank')
    // window['filter'] = {
    //   src: base64Head + ref.data
    // }
    // window.open('/#/print-preview-web')
    base64Download(
      'pdf',
      ref.data,
      `合同${format(new Date(new Date().getTime()), 'yyyy-MM-dd HH:mm:ss')}.pdf`
    )
  })
}
// 打开审核
function handleCheck(row) {
  let idArr = row.id ? [row.id] : ids.value
  checkDia.value = true
  checkForm.value = {
    approvalOpinion: '',
    approvalResult: row.approvalResult || '1',
    orderIds: idArr
  }
}
// 保存审核
function saveCheck() {
  proxy.$refs.checkRef.validate(async valid => {
    if (valid) {
      supervisionSave(checkForm.value).then(res => {
        proxy.$modal.msgSuccess('审核成功')
        checkDia.value = false
        getList()
      })
    }
  })
}
//打开上传合同弹窗
function uploadContract(row) {
  /***订单模块 */
  diaParam.value.open = true
  diaParam.value.multiple = true // 是否多选
  diaParam.value.title = row.customerName // 是否多选
  diaParam.value.queryParams = {
    partya: row.customerId, // 根据客户id查询合同列表
    uploadType: '1'
  }
  diaParam.value.initData = {
    ...row
  }
}

// 确认关联合同
function saveFn(data) {
  console.log('data=>', data)
  let param = {
    contractList: data.selectData.filter(e => e.rcId),
    contractRemark: data.formData.contractRemark,
    orderId: data.formData.id
  }
  supervisionContract(param).then(res => {
    getList()
  })
}

// 导入弹窗
const uploadDia = ref({
  title: '导入合同',
  uploadType: 'contract',
  open: false,
  message: ''
})
const uploadType = {
  remark: ['.xls', '.xlsx'],
  contract: ['.rar', '.zip', '.doc', '.docx', '.pdf', '.jpg', '.png']
}
// 获取培训产业模板链接/file/系统模板文件/培训产业登记表V1_20230728155654A001.xls
const downUrl = async function downUrl() {
  const url = await commonStore.getUploadTemplateDown(
    'contract_remark_template'
  )
  // console.info('url', url)
  window.open(url, '_blank')
}
/**导入数据 限制条件
 *
 * @param {*} rawFile
 */
const uploadLoading = ref(false)
function beforeAvatarUpload(rawFile) {
  console.log('rawFile==>', rawFile)
  // const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  // const allowType = uploadType[uploadDia.value.uploadType].indexOf(ext) > -1
  // const isLt2M = rawFile.size / 1024 / 1024 < 200

  // if (!allowType) {
  //   proxy.$message.error(
  //     `上传文件只能是${uploadType[uploadDia.value.uploadType]
  //       .toString()
  //       .replace(/\./g, '')
  //       .replace(/,/g, '、')}格式!`
  //   )
  // } else if (!isLt2M) {
  //   proxy.$message.error('上传文件大小不能超过 200MB!')
  // }
  // return allowType && isLt2M
}

const filesArr = ref([])
function handleChange(file, files) {
  filesArr.value = files.map(e => e.raw)
  // console.log('filesArr.value==>', filesArr.value)
}
// 移除文件
function handleRemove(file, files) {
  // console.log('file===>', file)
  // console.log('files===>', files)
  filesArr.value = files.map(e => e.raw)
}
// 超出时
const handleExceed = files => {
  proxy.$modal.msgError('超出文件限制')
}
// 上传文件
async function requestFile(params) {
  uploadLoading.value = true
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  // uploadData.append('type', formData.value.businessType)
  try {
    let res = await importRemark(uploadData)
    uploadLoading.value = false
    if (res.code === 200) {
      // proxy.$modal.msgSuccess('导入成功')
      uploadDia.value.message = res.data
      proxy.$refs.uploadRef.clearFiles()
      getList()
    }
  } catch (error) {
    uploadLoading.value = false
    console.log('error===>', error)
    proxy.$refs.uploadRef.clearFiles()
    uploadDia.value.message = error.toString().replace('Error:', '')
  }
}
// 关闭导入弹窗
function closeUpload() {
  uploadDia.value.open = false
  uploadDia.value.message = ''
  filesArr.value = []
  proxy.$refs.uploadRef.clearFiles()
}
// 确定上传
const submitFileForm = async () => {
  if (filesArr.value.length == 0) {
    return proxy.$modal.msgError('请先选择文件')
  }
  if (uploadDia.value.uploadType == 'remark') {
    proxy.$refs.uploadRef.submit()
  } else {
    if (filesArr.value.length > 20) {
      return proxy.$modal.msgError('一次最多上传20个文件')
    }
    uploadLoading.value = true
    let uploadData = new FormData()
    filesArr.value.forEach(e => {
      uploadData.append('file', e)
    })
    // uploadData.append('type', formData.value.businessType)
    try {
      let res = await importContract(uploadData)
      uploadLoading.value = false
      if (res.code === 200) {
        // proxy.$modal.msgSuccess('导入成功')
        uploadDia.value.message = res.data
        getList()
      }
    } catch (error) {
      uploadLoading.value = false
      console.log('error===>', error)
      uploadDia.value.message = error.toString().replace('Error:', '')
    }
  }
}

init()
</script>
<style scoped>
.search-drawer-retract {
  color: #999999;
}
</style>
